<?php
use app\models\Nav;

/*导航信息*/
function smarty_block_navigation($params, $content, Smarty_Internal_Template $template, &$repeat)
{
    $app_id = Yii::$app->params['app_id'];
    $nav = Nav::find()
            ->select(['name', 'parentid', 'allchildid', 'preview', 'outside', 'url', 'url_target', 'args'])
            ->where('app_id = :app_id and parentid = :pid and display = 2', [':app_id' => $app_id, ':pid' => $params['parentid']])
           	->orderBy(['sort' => SORT_ASC])
            ->asArray()->all();
    // P($nav);
    if(!is_null($nav)){
        /*取出所有的导航 用于匹配栏目下的所有子url*/
        $allnav = Nav::find()
            ->select(['navid', 'url'])
            ->where('app_id = :app_id and display = 2', [':app_id' => $app_id])
            ->asArray()->all();
        $allNavId = [];
        $allUrl = [];
        foreach($allnav as $k => $v){
            array_push($allNavId, $v['navid']);
            $allUrl[$v['navid']] = $v['url'];
        }
        // P($allNavId, false);
        // P($allUrl);

        foreach($nav as $k => $v){
            $nav[$k]['allchildurl'] = [$v['url']];
            /*如果有子栏目，取出所有的子url*/
            if(!empty($v['allchildid'])){
                $allchildidArr = explode(',', $v['allchildid']);
                foreach($allchildidArr as $k1 => $v1){
                    if(in_array($v1, $allNavId) and !empty($allUrl[$v1])){
                        array_push($nav[$k]['allchildurl'], $allUrl[$v1]);
                    }
                }
            }

            $nav[$k]['target'] = ($nav[$k]['url_target'] == 1)?'_self':'_blank';
            unset($nav[$k]['outside']);
            unset($nav[$k]['url_target']);
            if(isset($v['url']) and ($v['outside'] == 1) and (substr($v['url'], 0, 7) != 'http://')){
                $nav[$k]['url'] = '/' . $nav[$k]['url'];
            }

        }



    }else{
    	$nav = [];
    }
    // P($nav);
    
    $template->assign("list", $nav);
    return $content;

}